package GUI;

import Entity.User;
import GUITOOl.*;
import Service.AddFriend;
import Utils.*;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.FontUIResource;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static java.lang.System.exit;

/**
 * The type Main frame.
 *
 * @author dzr, wyc, zry
 * @version 1.0
 */
public class MainFrame extends JFrame {
    /**
     * The My uid.
     */
    int my_uid;
    /**
     * The My name.
     */
    String my_name;
    /**
     * The Profile id.
     */
    int profileID;
    /**
     * The Sex.
     */
    String sex;
    /**
     * The Birthday.
     */
    String birthday;
    /**
     * The Info.
     */
    JPanel info;
    /**
     * The Functions.
     */
    JPanel functions;
    /**
     * The Friend list.
     */
    JPanel friendList;
    /**
     * The Portrait.
     */
    JLabel portrait;
    /**
     * The Uid text.
     */
    JLabel uid_text;
    /**
     * The Name text.
     */
    JLabel name_text;
    /**
     * The Add fri.
     */
    JButton addFri;
    /**
     * The Search.
     */
    JLabel search;
    /**
     * The MainPane.
     */
    JScrollPane jp;

    /**
     * Instantiates a new Main frame.
     *
     * @param my_uid    the my uid
     * @param profileID the profile id
     * @param my_name   the my name
     * @param sex       the sex
     * @param birthday  the birthday
     */
    public MainFrame(int my_uid, int profileID, String my_name, String sex, String birthday){
        this.my_uid = my_uid;
        this.profileID = profileID;
        this.my_name = my_name;
        this.sex = sex;
        this.birthday = birthday;
        init();
    }

    /**
     * Init.
     */
    public void init(){

        MyLineBorder myLineBorder = new MyLineBorder(new Color(192, 192, 192), 1 , true);
        Color bgColor=new Color(255, 255, 255);

        this.getContentPane().setBackground(bgColor);
        this.setTitle("feather_chat");
        this.setFont(new Font("MV Boli",0,14));
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setLayout(new BorderLayout());
        this.setLocation(666,366);

        Image frameImage=ImageIconUtils.getRawPicture("picture.png").getImage();
        this.setIconImage(frameImage);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        portrait = new JLabel();
        portrait.setSize(150, 150);
        portrait.setIcon(ImageIconUtils.getProfile(profileID, portrait.getWidth(), portrait.getHeight()));
        portrait.setBorder(BorderFactory.createLineBorder(new Color(0, 0, 0)));
        portrait.addMouseListener(new updateInfo());
        info = new JPanel();
        info.setSize(380, 200);
        info.setLayout(new BorderLayout());
        name_text = new JLabel();
        name_text.setText(my_name);
        name_text.setFont(new Font("微软雅黑",0,20));
        uid_text = new JLabel();
        uid_text.setText("id "+my_uid + "");
        uid_text.setFont(new Font("微软雅黑",0,16));
        addFri = new MyButton("添加新好友");
        addFri.setFont(new Font("微软雅黑",0,16));
        addFri.setBackground(bgColor);
        addFri.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JDialog dialog = new JDialog(MainFrame.this,"friendAdd");
                dialog.setLayout(new FlowLayout());
                dialog.getContentPane().setBackground(bgColor);
                Box box1, box2, boxMain;

                JPanel panel_image=new JPanel();
                panel_image.setLayout(null);
                panel_image.setPreferredSize(new Dimension(120, 120));
                panel_image.setBackground(bgColor);
                ImageIcon image=ImageIconUtils.getRawPicture("add.png");
                JLabel background=new JLabel(image);
                background.setBounds(0,20,100,100);
                panel_image.add(background);
                dialog.add(panel_image,BorderLayout.WEST);

                box1 = Box.createHorizontalBox();
                box1.setBackground(bgColor);
                search=new JLabel("好友ID");
                search.setFont(new Font("微软雅黑",0,16));
                box1.add(search);
                box1.add(Box.createHorizontalStrut(40));
                JTextField f_uid_text = new JTextField();
                f_uid_text.setBorder(myLineBorder);
                f_uid_text.setSize(150,30);
                box1.add(f_uid_text);
                box2 = Box.createHorizontalBox();
                box2.setBackground(bgColor);
                JButton b1, b2;
                b1 = new MyButton("添加");
                b1.setFont(new Font("微软雅黑",0,16));
                b1.setBackground(bgColor);
                b1.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if(Validate.isEmpty(f_uid_text)){
                            new showMessageFrame("id不能为空");
                        }else if (!Validate.isDigital(f_uid_text)){
                            new showMessageFrame("uid格式错误");
                        }else{
                            try {
                                AddFriend.addFri(my_uid, Integer.parseInt(f_uid_text.getText()));
                            } catch (IOException ioException) {
                                ioException.printStackTrace();
                            }
                        }
                    }
                });
                b2 = new MyButton("返回");
                b2.setFont(new Font("微软雅黑",0,16));
                b2.setBounds(0,0,100,50);
                b2.setBackground(bgColor);
                b2.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialog.dispose();
                    }
                });
                box2.add(Box.createHorizontalStrut(40));
                box2.add(b1);
                box2.add(Box.createHorizontalStrut(80));
                box2.add(b2);
                box2.setBackground(bgColor);
                boxMain=Box.createVerticalBox();
                boxMain.add(Box.createVerticalStrut(20));
                boxMain.add(box1);
                boxMain.add(Box.createVerticalStrut(30));
                boxMain.add(box2);
                boxMain.setBackground(bgColor);
                dialog.add(boxMain,BorderLayout.CENTER);
                dialog.setSize(400, 200);
                dialog.setLocation(GetWindowsSize.getWindowsSize().width / 2 - dialog.getWidth() / 2, GetWindowsSize.getWindowsSize().height / 2 - dialog.getHeight() / 2);
                dialog.getContentPane().setBackground(bgColor);
                dialog.setVisible(true);
                dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            }
        });
        Box box = Box.createVerticalBox();
        box.add(Box.createHorizontalStrut(80));
        box.add(name_text);
        box.add(Box.createHorizontalStrut(80));
        box.add(uid_text);
        box.add(Box.createHorizontalStrut(80));
        box.add(addFri);
        box.setBackground(bgColor);
        info.add(portrait,BorderLayout.WEST);
        info.add(box,BorderLayout.CENTER);
        info.setBackground(bgColor);
        functions = new JPanel(new FlowLayout());
        functions.setSize(400, 100);
        functions.setBackground(bgColor);
        friendList=new JPanel();
        friendList.setBackground(bgColor);
        friendList.setLayout(new FlowLayout());
        HashMap<Integer, User> friends_online = ThreadManage.getInstance().getClientThreads().get(my_uid).getFriends_online();
        ArrayList<User> uArray=new ArrayList<>();
        for(Map.Entry<Integer,User> entry:friends_online.entrySet()){
            uArray.add(entry.getValue());
        }
        FriListModel buddy=new FriListModel(uArray);

        @SuppressWarnings("rawtypes")
        JList buddyList = new JList(buddy);
        buddyList.setCellRenderer(new FriListCellRenderer());
        buddyList.setFont(new Font(Font.SERIF, Font.PLAIN, 18));
        buddyList.setPreferredSize(new Dimension(350, 500));
        buddyList.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e){
                if(e.getClickCount()==2){
                    int i=buddyList.getSelectedIndex();
                    User friend=uArray.get(i);
                    if (ChatManage.hasChat(friend.getUid())){
                        ChatManage.getChat(friend.getUid()).setExtendedState(JFrame.NORMAL);
                    }else{
                        ChatFrame chatFrame = new ChatFrame(my_name, my_uid, friend.getUsername(), friend.getUid());
                        ChatManage.addChat(friend.getUid(), chatFrame);
                    }
                }
            }
        });
        buddyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        buddyList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ;
            }
        });

        Box blank=Box.createVerticalBox();
        blank.setBackground(bgColor);
        blank.add(Box.createVerticalStrut(100));

        JPanel list=new JPanel();
        JLabel friTitle=new JLabel("—————在 线 好 友—————");
        friTitle.setForeground(MyButton.sky1);
        friTitle.setFont(new Font("微软雅黑",0,20));
        friTitle.setSize(30,30);

        list.setLayout(null);
        list.setPreferredSize(new Dimension(0,50));
        list.setBackground(bgColor);
        ImageIcon image=ImageIconUtils.getRawPicture("main.png");
        JLabel background=new JLabel(image);
        background.setBounds(-10,0,400,50);
        list.add(background);

        JPanel panel_top=new JPanel();
        panel_top.setLayout(new BorderLayout());
        panel_top.add(info,BorderLayout.NORTH);
        panel_top.add(list,BorderLayout.SOUTH);
        this.add(panel_top,BorderLayout.NORTH);

        jp = new JScrollPane(
                buddyList,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
                );
        jp.setBorder(null);
        jp.getVerticalScrollBar().setUI(new MyScrollBarUI());
        jp.getHorizontalScrollBar().setUI(new MyScrollBarUI());

        jp.setBorder(myLineBorder);
        jp.setSize(380,600);
        jp.setVisible(buddy.getSize() != 0);
        friendList.add(jp);
        friendList.setVisible(true);
        this.add(friendList,BorderLayout.CENTER);

        JPanel panel_bottom=new JPanel();
        panel_bottom.setPreferredSize(new Dimension(0, 130));
        panel_bottom.setBackground(bgColor);
        ImageIcon image1=ImageIconUtils.getRawPicture("bottom3.png");
        JLabel background1=new JLabel(image1);
        background1.setBounds(0,0,380,130);
        panel_bottom.add(background1);
        add(panel_bottom,BorderLayout.SOUTH);

        setBounds(1488, 126, 380, 800);
        setVisible(true);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                UIManager.put("OptionPane.buttonFont", new FontUIResource(new Font("微软雅黑", Font.PLAIN, 13)));
                UIManager.put("OptionPane.messageFont", new FontUIResource(new Font("微软雅黑", Font.PLAIN, 13)));
                int result = JOptionPane.showConfirmDialog(MainFrame.this,
                        "确认退出？",
                        "提示",
                        JOptionPane.YES_NO_OPTION);
                if (result == JOptionPane.YES_OPTION){
                    exitProcessor();
                }
            }
        });
        this.setVisible(true);
    }

    /**
     * Update friend status.
     *
     * @param friend   the friend
     * @param isOnline the is online
     */
    public void updateFriendStatus(User friend, boolean isOnline, boolean visible){
        if(isOnline){
            if (visible) {
                new showMessageFrame(friend.getUsername() + "上线啦");
            }
        }else{
            if (visible) {
                new showMessageFrame(friend.getUsername() + "下线啦");
            }
        }
        HashMap<Integer, User> friends_online = ThreadManage.getInstance().getClientThreads().get(my_uid).getFriends_online();
        ArrayList<User> uArray=new ArrayList<>();
        for(Map.Entry<Integer,User> entry:friends_online.entrySet()){
            uArray.add(entry.getValue());
        }
        FriListModel buddy=new FriListModel(uArray);
        @SuppressWarnings("rawtypes")
        JList buddyList = new JList(buddy);
        buddyList.setCellRenderer(new FriListCellRenderer());
        buddyList.setFont(new Font(Font.SERIF, Font.PLAIN, 18));
        buddyList.setPreferredSize(new Dimension(350, 500));
        buddyList.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e){
                if(e.getClickCount()==2){
                    int i=buddyList.getSelectedIndex();
                    User friend=uArray.get(i);
                    ChatFrame chatFrame = new ChatFrame(my_name, my_uid, friend.getUsername(), friend.getUid());
                    ChatManage.addChat(friend.getUid(), chatFrame);
                }
            }
        });
        buddyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        buddyList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ;
            }
        });
        jp.setViewportView(buddyList);
        jp.setVisible(buddy.getSize() != 0);
        jp.updateUI();
        friendList.repaint();
        this.validate();
        this.repaint();
    }

    /**
     * The type Update info.
     *
     * @author dzr
     * @version 1.0
     */
    class updateInfo extends MouseAdapter {
        public void mouseClicked(MouseEvent e){
            if(e.getClickCount()==2){
                new InfoFrame(my_uid,profileID,my_name,sex,birthday);
            }
        }
    }

    /**
     * Update info.
     *
     * @param my_name   the my name
     * @param profileID the profile id
     * @param sex       the sex
     * @param birthday  the birthday
     */
    public void updateInfo(String my_name, int profileID, String sex, String birthday){
        this.my_name = my_name;
        this.profileID = profileID;
        this.sex = sex;
        this.birthday = birthday;
        portrait.setIcon(ImageIconUtils.getProfile(profileID, portrait.getWidth(), portrait.getHeight()));
        name_text.setText(my_name);
        uid_text.setText("id "+my_uid + "");
        this.repaint();
    }

    /**
     * Exit processor.
     */
    public void exitProcessor(){
        ThreadManage.getInstance().closeClientThread(my_uid);
        exit(0);
    }
}


